<template>
  <a-row :gutter="24" class="search-row">
    <a-col :span="24">
      <x-card>
        <div slot="content" class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="24" >
              <a-col :span="6">
                <a-form-item
                  label="数据来源"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-select
                    allow-clear
                    placeholder="请选择数据来源"
                    v-model="selectedCheckTypes"
                    mode="multiple"
                    @change="handleCheckTypeChange"
                    style="height: 40px; overflow-y: auto;">
                    <a-select-option value="全部">全部</a-select-option>
                    <a-select-option v-for="item in CheckTypeList" :key="item.id" :value="item.item">{{
                      item.item
                    }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  label="违章单位"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-tree-select
                    allowClear
                    showSearch
                    style="width:100%;"
                    tree-node-filter-prop="title"
                    v-model="OrganizationName"
                    :treeData="QHSEOrganizationTree"
                    v-if="QHSEOrganizationTree.length"
                    @change="handleOrganizationSelectChange"
                    :defaultExpandAll="true"
                    :defaultExpandedKeys="defaultExpandedKeys"
                    :replaceFields="replaceFields"
                    ref="tree"
                    placeholder="请选择违章单位"
                    :title="OrganizationName"/>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  label="开始时间"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-date-picker style="width: 100%" format="YYYY-MM-DD" @change="onChange1" :style="{width: '100%'}" v-model="TimeOn"/>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  label="结束时间"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-date-picker style="width: 100%" format="YYYY-MM-DD" @change="onChange2" :style="{width: '100%'}" v-model="TimeEnd"/>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="检查单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select
                    allowClear
                    showSearch
                    style="width: 100%;"
                    tree-node-filter-prop="title"
                    v-model="CheckOrganizationName"
                    :treeData="QHSEOrganizationTree1"
                    v-if="QHSEOrganizationTree1.length"
                    @change="handleCheckOrganizationSelectChange"
                    :defaultExpandAll="true"
                    :defaultExpandedKeys="defaultExpandedKeys"
                    :replaceFields="replaceFields"
                    ref="tree"
                    placeholder="请选择检查单位"
                    :title="CheckOrganizationName"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item></a-form-item>
              </a-col>
              <a-col :span="6" class="search-buttons">
                <a-button type="primary" :loading="loading2" @click="handleClick">{{ loading2 ? '查询中...' : '查询' }}</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
                <a-button type="primary" @click="handleExport" :loading="batchExportLoading"><a-icon type="export"/>导出数据</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </x-card>
      <a-row :gutter="48" class="search-row">
        <a-col :span="24">
          <a-divider orientation="left" style="font-weight: bold; margin-bottom: 2px;margin-top: -2px"> 违章原因分析
          </a-divider>
          <a-card style="overflow-y: hidden" :style="{ height: cardHeight }">
            <!-- <a-progress
              class="prog"
              type="circle"
              :strokeWidth="10"
              :percent="percent"
              :width="200"
              v-if="loading"
            /> -->
            <!--违章原因-->
            <a-row style="width: 100%; height: 600px; margin-top: 20px">
              <a-col :span="24">
                <div id="bar-chart-container1" style="width: 100%; height: 600px;"></div>
              </a-col>
            </a-row>
            <!--违章性质-->
            <a-row style="width: 100%; height: 600px;">
              <a-col :span="24">
                <div id="bar-chart-container2" style="width: 100%; height: 500px;"></div>
              </a-col>
            </a-row>
            <!--年龄-->
            <a-row style="width: 100%; height: 600px;">
              <a-col :span="24">
                <div id="bar-chart-container3" style="width: 100%; height: 500px;"></div>
              </a-col>
            </a-row>
            <!--工龄-->
            <a-row style="width: 100%; height: 600px;">
              <a-col :span="24">
                <div id="bar-chart-container4" style="width: 100%; height: 500px;"></div>
              </a-col>
            </a-row>
            <!--用工性质-->
            <a-row style="width: 100%; height: 600px;">
              <a-col :span="24">
                <div id="bar-chart-container5" style="width: 100%; height: 500px;"></div>
              </a-col>
            </a-row>
            <!--专业-->
            <a-row style="width: 100%; height: 600px;">
              <a-col :span="24">
                <div id="bar-chart-container6" style="width: 100%; height: 500px;"></div>
              </a-col>
            </a-row>
          </a-card>
        </a-col>
      </a-row>
    </a-col>
  </a-row>
</template>
<script>
  import { STable, XCard, XDown } from '@/components'
  import { getQHSEOrganizationTree } from '@/api/modular/system/QHSEOrganization'
  // import {
  //   getVioWorkYearsAnalysis,
  //   getVioWorkYearsTypeDefectAnalysis,
  //   getVioCategoryAnalysis,
  //   getVioWorkSpecialtyAnalysis,
  //   getVioAgeAnalysis,
  //   getVioEmployeeTypeAnalysis
  // } from '@/api/modular/system/vioWorkYearAnalysisManage'
  import {
    getVioCauseAnalysis,
    getVioTypeAnalysis,
    getVioAgeAnalysis,
    getVioWorkYearsAnalysis,
    getVioEmployeeTypeAnalysis,
    getVioWorkSpecialityAnalysis
  } from '@/api/modular/system/violationCauseAnalysis'
  import { getCheckTypeList } from '@/api/modular/system/QHSEDictionary'
  import * as echarts from 'echarts'
  import moment from 'moment'
  import { mapGetters } from 'vuex'
  import * as XLSX from 'xlsx'
  export default {
    components: {
      XDown,
      XCard,
      STable
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        // 获取参数
        queryParam: {
          TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
          TimeEnd: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
        },
        selectedValue: null,
        batchExportLoading: false,
        TimeOn: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months'),
        TimeEnd: moment(new Date(), 'YYYY-MM-DD'),
        chart: false,
        tableData1: [],
        tableData2: [[]],
        tableData3: [[]],
        tableData4: [[]],
        tableData5: [[]],
        tableData6: [[]],
        QHSEOrganizationTree: [],
        QHSEOrganizationTree1: [],
        selectedCheckTypes: [],
        CheckTypeList: [],
        defaultExpandedKeys: [],
        replaceFields: {
          children: 'children',
          title: 'title',
          key: 'workflowId',
          value: 'id',
          parentId: 'parentId'
        },
        OrganizationName: '',
        CheckOrganizationName: '',
        loading: true,
        loading2: false,
        percent: 0,
        cardHeight: '400px',
        secondOraName: {
          id: ''
        }
      }
    },
    created() {
      this.getQHSEOrganizationTree()
      this.getCheckTypeList()
    },
    computed: {
      ...mapGetters(['userInfo'])
      },
    watch: {
      percent(newVal) {
        if (newVal === 100) {
          setTimeout(() => {
            this.percent = 1
            // this.loading = false
            this.loading2 = false
          }, 500)
        }
      }
    },
    methods: {
      exportWholePageToExcel() {
      const tablesData = [
        { data: this.tableData1, name: '违章原因' },
        { data: this.tableData2, name: '违章性质' },
        { data: this.tableData3, name: '年龄' },
        { data: this.tableData4, name: '工龄' },
        { data: this.tableData5, name: '用工性质' },
        { data: this.tableData6, name: '作业专业' }
      ]
      console.log(tablesData)
       // 创建一个工作簿
      const workbook = XLSX.utils.book_new()
     // 遍历每个表格的数据，将其转换为对应的工作表并添加到工作簿
        tablesData.forEach(({ data, name }, index) => {
          // 确保数据是一个二维数组
          if (Array.isArray(data) || Array.isArray(data[0])) {
            // 将每个数组转换为对应的工作表
            const worksheet = XLSX.utils.json_to_sheet(data)
            // 将工作表添加到工作簿，并使用表格名称作为工作表名称
            XLSX.utils.book_append_sheet(workbook, worksheet, name)
          } else {
            console.error(`Data for table ${name} is not a valid two-dimensional array`)
          }
        })
        // 生成Excel文件
        XLSX.writeFile(workbook, '违章原因分析.xlsx')
        this.batchExportLoading = false
      },
      handleExport() {
        this.batchExportLoading = true
        this.exportWholePageToExcel()
      },
      renderBarChart(data, containerId, chartType) {
        const barChartContainer = document.getElementById(containerId)
        const barChart = echarts.init(barChartContainer)
        const barChartData = data.map((item) => ({
          value: item.value,
          name: item.name
        }))
        const barChartOptions = {
          title: {
            text: '',
            textStyle: {
              fontWeight: 'bold',
              fontSize: 20
            },
            left: 'center' // 标题水平居中
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            containLabel: true,
            top: 60
          },
          xAxis: {
            type: 'category',
            data: null,
            axisLabel: {
              interval: 1
            }
          },
          yAxis: {
            type: chartType === 'vertical' ? 'value' : 'category',
            data: null
          },
          series: [
            {
              type: 'bar',
              data: barChartData,
              barWidth: '40%',
              label: {
                show: true,
                position: 'top',
                  formatter: function (params) {
                    // 只显示偶数索引的标签
                    return params.dataIndex % 2 === 0 ? params.value : ''
                  }
              }
            }
          ]
        }
        if (containerId === 'bar-chart-container1') {
          barChartOptions.title.text = '违章原因'
          barChartOptions.yAxis.type = 'value'
          barChartOptions.xAxis.data = barChartData.map(item => item.name)
          barChartOptions.xAxis.axisLabel = {
              formatter: function (value) {
              return value.split('').join('\n') // 在每个字符之间添加换行符
            }
          }
        }
        if (barChartData.length > 0) {
          barChart.setOption(barChartOptions)
        }
      },
      renderMulBarChart(data, containerId, chartType) {
      const barChartContainer = document.getElementById(containerId)
      const barChart = echarts.init(barChartContainer)
      if (data.item === undefined) {
        return
      }
      const barChartData = data.item
      const barChartOption = {
        title: {
          text: '',
          textStyle: {
            fontWeight: 'bold',
            fontSize: 20
          },
          left: 'center' // 标题水平居中
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          orient: 'horizontal',
          x: 'center',
          y: 'bottom',
          textStyle: {
            fontSize: 16
          }
        },
        grid: {
          containLabel: true,
          top: 60
        },
        xAxis: {
          type: 'category'
        },
        yAxis: {
          type: 'value'
        },
        series: []
      }
      const headerRow = barChartData[0]
      for (var i = 1; i < headerRow.length; i++) {
        var dataObj = {
          name: headerRow[i],
          type: 'bar',
          data: barChartData.slice(1).map(row => row[i]),
          label: {
              show: true,
              position: 'top',
              formatter: function (params) {
                // 根据seriesIndex来决定是否显示标签
                if (params.seriesIndex % 2 === 0) {
                  return params.value
                } else {
                  return ''
                }
              }
            }
        }
        barChartOption.series.push(dataObj)
      }
      barChartOption.title.text = barChartData[0][0]
      // 超过13个专业竖着显示横坐标
      if (barChartData.length > 13) {
          barChartOption.xAxis.axisLabel = {
            formatter: function (value) {
              return value.split('').join('\n') // 在每个字符之间添加换行符
            },
            fontSize: 14
        }
      } else {
        barChartOption.xAxis.axisLabel = {
          interval: 0,
          formatter: null,
          fontSize: 14 // 设置较大的字体大小
        }
      }
      barChartOption.xAxis.data = barChartData.slice(1).map(row => row[0])
      if (barChartData.length > 0) {
        barChart.setOption(barChartOption)
      }
      barChart.setOption(barChartOption)
    },
      handleCheckTypeChange(value) {
        if (value.includes('全部')) {
          // 选中了全部选项，将所有选项都添加到 selectedCheckTypes 中
          this.selectedCheckTypes = this.CheckTypeList.map(item => item.item)
        }
        this.queryParam.CheckType = this.selectedCheckTypes.map(option => option.toString())
      },
      handleClick() {
        if (this.queryParam.CheckType.length === 0 || !this.queryParam.OrganizationName || !this.TimeOn || !this.TimeEnd) {
          this.$message.warning('请填写完整的查询条件')
        } else { // 调用加载数据的方法
          // this.loading = true
          this.loading2 = true
          this.percent = 1
          this.loadData1()
          this.loadData2()
          this.loadData3()
          this.loadData4()
          this.loadData5()
          this.loadData6()
          this.chart = true
          this.cardHeight = 'auto'
          // console.log(this.queryParam)
        }
      },
      // 加载数据
      loadData1() {
        getVioCauseAnalysis(this.queryParam)
          .then(res => {
            this.tableData1 = res.data
            // console.log('原因：', res.data)
            this.renderBarChart(res.data, 'bar-chart-container1', 'horizontal')
            this.percent += 16
          })
          .catch(error => {
            // 处理请求错误
            console.error(error)
            this.loading2 = false
            // 显示错误信息
            this.$message.error('获取数据失败')
          })
      },
      // 加载数据
      loadData2() {
        getVioTypeAnalysis(this.queryParam)
          .then(res => {
            this.tableData2 = res.data.item
            this.renderMulBarChart(res.data, 'bar-chart-container2', 'vertical')
            this.percent += 17
          })
          .catch(error => {
            // 处理请求错误
            console.error(error)
            this.loading2 = false
            // 显示错误信息
            this.$message.error('获取数据失败')
          })
      },
      // 加载数据
      loadData3() {
        getVioAgeAnalysis(this.queryParam)
          .then(res => {
            this.tableData3 = res.data.item
            this.renderMulBarChart(res.data, 'bar-chart-container3', 'vertical')
            this.percent += 17
          })
          .catch(error => {
            // 处理请求错误
            console.error(error)
            this.loading2 = false
            // 显示错误信息
            this.$message.error('获取数据失败')
          })
      },
      loadData4() {
        getVioWorkYearsAnalysis(this.queryParam)
          .then(res => {
            this.tableData4 = res.data.item
            this.renderMulBarChart(res.data, 'bar-chart-container4', 'vertical')
            this.percent += 17
          })
          .catch(error => {
            // 处理请求错误
            console.error(error)
            this.loading2 = false
            // 显示错误信息
            this.$message.error('获取数据失败')
          })
      },
      loadData5() {
        getVioEmployeeTypeAnalysis(this.queryParam)
          .then(res => {
            this.tableData5 = res.data.item
            this.renderMulBarChart(res.data, 'bar-chart-container5', 'vertical')
            this.percent += 16
          })
          .catch(error => {
            // 处理请求错误
            console.error(error)
            this.loading2 = false
            // 显示错误信息
            this.$message.error('获取数据失败')
          })
      },
      loadData6() {
        getVioWorkSpecialityAnalysis(this.queryParam)
          .then(res => {
            this.tableData6 = res.data.item
            this.renderMulBarChart(res.data, 'bar-chart-container6', 'vertical')
            this.percent += 16
          })
          .catch(error => {
            // 处理请求错误
            console.error(error)
            this.loading2 = false
            // 显示错误信息
            this.$message.error('获取数据失败')
          })
      },
      onChange1(date, dateString) {
        // console.log(dateString, date)
        if (this.queryParam.TimeEnd && dateString) {
          if (dateString > this.queryParam.TimeEnd) {
            this.$message.error('开始时间不能晚于结束时间')
            this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
            this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
            this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
            this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
          } else {
            this.queryParam.TimeOn = dateString
          }
        } else {
          this.queryParam.TimeOn = dateString
        }
      },
      onChange2(date, dateString) {
        if (this.queryParam.TimeOn && dateString) {
          if (this.queryParam.TimeOn > dateString) {
            this.$message.error('开始时间不能晚于结束时间')
            this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
            this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
            this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
            this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
          } else {
            this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
          }
        } else {
          this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
        }
      },
      // 更改违章单位
      handleOrganizationSelectChange(val, opt, extra) {
        if (extra.triggerNode === undefined) {
          this.queryParam.OrganizationName = null
          this.queryParam.OrganizationId = null
        } else {
          const option = extra.triggerNode._props.title
          this.queryParam.OrganizationName = option
          this.queryParam.OrganizationId = extra.triggerNode._props.value
          this.OrganizationName = this.queryParam.OrganizationName
        }
      },
      handleCheckOrganizationSelectChange(val, opt, extra) {
        if (extra.triggerNode === undefined) {
          this.queryParam.CheckOrganizationName = null
          this.queryParam.CheckOrganizationId = null
        } else {
          const option = extra.triggerNode._props.title
          this.queryParam.CheckOrganizationName = option
          this.queryParam.CheckOrganizationId = extra.triggerNode._props.value
          this.CheckOrganizationName = this.queryParam.CheckOrganizationName
        }
      },
    getQHSEOrganizationTree () {
      this.secondOraName.id = this.userInfo.secondOrganizationName
      getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
      // console.log('tree:', res.data)
      this.treeLoading = false
      if (!res.success) {
          return
      }
      this.QHSEOrganizationTree = res.data
      if (res.data.length === 0) {
        this.secondOraName.id = '机关总部'
        getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
          this.QHSEOrganizationTree = res.data
          this.queryParam.OrganizationName = res.data[0].title
          this.queryParam.OrganizationId = res.data[0].id
          this.OrganizationName = this.queryParam.OrganizationName
        })
      } else {
        this.queryParam.OrganizationName = res.data[0].title
        this.queryParam.OrganizationId = res.data[0].id
        this.OrganizationName = this.queryParam.OrganizationName
      }
     })
     this.secondOraName.id = '安检院'
     getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
       // console.log('tree:', res.data)
       this.treeLoading = false
       if (!res.success) {
         return
       }
       this.QHSEOrganizationTree1 = res.data
       this.queryParam.CheckOrganizationName = res.data[0].title
       this.queryParam.CheckOrganizationId = res.data[0].id
       this.CheckOrganizationName = this.queryParam.CheckOrganizationName
     })
    },
      // 检查类型-数据来源
      getCheckTypeList(text) {
        getCheckTypeList().then((res) => {
          this.CheckTypeList = res.data
          const select = '全部'
          this.handleCheckTypeChange(select)
        })
      },
      reset() {
        this.queryParam = {
          TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
          TimeEnd: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
        }
        this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
        this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
        this.selectedCheckTypes = []
      }
    }
  }
</script>
<style lang="less" scoped>
  .table-operator {
    margin-bottom: 18px;
  }

  button {
    margin-right: 8px;
  }

  .search-row {
    display: flex;
    align-items: center;
  }

  .search-buttons {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
  }

  .chart-container {
    margin-top: 20px;
    /* 调整顶部边距 */
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
  }
  .prog {
  position: relative;
  top: 90px;
  left: 42%;
}
/deep/.ant-progress-text {
  font-size: 2rem;
}
/deep/.ant-progress-circle-path {
  animation: rotate 3s linear infinite;
  transform-origin: center center;
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
